# 导入必要的库和模块
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import pickle
from tqdm import tqdm

# 设置matplotlib支持中文和负号显示
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False

# 加载数字数据集
digits = load_digits()
X, y = digits.data, digits.target

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 0
best_knn = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in tqdm(range(1, 41), desc='Training KNN models'):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    accuracies.append(accuracy)
    
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn = knn

# 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl', 'wb') as f:
    pickle.dump(best_knn, f)

# 打印最佳准确率和相应的k值
print(f"最佳准确率: {best_accuracy:.4f}")
print(f"最佳k值: {best_k}")

# 绘制k值与准确率的关系图
plt.figure(figsize=(10, 6))
plt.plot(range(1, 41), accuracies, marker='o', label='Accuracy')
plt.title('K值与准确率的关系')
plt.xlabel('K值')
plt.ylabel('准确率')
plt.grid(True)
plt.legend()

# 添加红色虚线和最佳k值标记
plt.axvline(x=best_k, color='red', linestyle='--', label='Best K')
plt.text(best_k, best_accuracy, f'({best_k}, {best_accuracy:.4f})', color='red', fontsize=12, ha='right')

# 保存图片
plt.savefig('knn_accuracy_plot.png')
plt.show()